package team.soi.cloud.api.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能描述: <br/>
 *
 * @author Soi <br/>
 * @version 1.0 2016/8/11 20:15
 * @see
 */
public class AccessFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(AccessFilter.class);

    private static final String PRE = "pre";
    private static final int FILTER_ORDER = 0;
    private static final boolean SHOULD_FILTER = true;
    private static final String ACCESS_TOKEN = "accessToken";
    private static final boolean ACCESS_TOKEN_NULL = false;
    private static final int ACCESS_DENIED = 401;

    /**
     * 返回一个字符串代表过滤器的类型 <br/>
     * pre：可以在请求被路由之前调用<br/>
     * routing：在路由请求时候被调用<br/>
     * post：在routing和error过滤器之后被调用<br/>
     * error：处理请求时发生错误时被调用<br/>
     *
     * @return filterType - String
     */
    @Override
    public String filterType() {
        return PRE;
    }

    /**
     * 通过int值来定义过滤器的执行顺序
     *
     * @return filterOrder - int
     */
    @Override
    public int filterOrder() {
        return FILTER_ORDER;
    }

    /**
     * 返回一个boolean类型来判断该过滤器是否要执行，所以通过此函数可实现过滤器的开关。
     *
     * @return shouldFilter - boolean
     */
    @Override
    public boolean shouldFilter() {
        return SHOULD_FILTER;
    }

    /**
     * 过滤器的具体逻辑
     *
     * @return Object
     */
    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        Object accessToken = request.getParameter(ACCESS_TOKEN);
        if (null == accessToken) {
            logger.warn("[{}] request to [{}],not found accessToken from request parameter", request.getMethod(),
                    request.getRequestURL());
            accessToken = request.getHeader(ACCESS_TOKEN);
        }
        if (null == accessToken) {
            context.setSendZuulResponse(ACCESS_TOKEN_NULL);
            context.setResponseStatusCode(ACCESS_DENIED);
        }
        return null;
    }
}
